package cn.hxt.basic.service.impl;

import cn.hxt.basic.constant.BaseConstants;
import cn.hxt.basic.exception.BusinessException;
import cn.hxt.basic.service.IVerifyCodeService;
import cn.hxt.basic.util.StrUtils;
import cn.hxt.user.domain.User;
import cn.hxt.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendSmsCode(Map<String, String> params) {
        //一，校验
        String phone = params.get("phone");
        String type = params.get("type");

        //判断手机号是否填写
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)) {
            throw new BusinessException("滚犊子！！手机号都不填！！");
        }

        String businessKey = "";
        //如果他是注册请求
        if ("register".equals(type)) {

            //判断手机号是否注册
            User user = userMapper.loadByPhone(phone);
            if (user != null) {
                throw new BusinessException("用户已存在了，傻杯！！！！！");
            }
            businessKey = BaseConstants.BUSINESS_REGISTER_PREFIX + phone;

            //如果是绑定请求，
        } else if ("binder".equals(type)) {
            businessKey = BaseConstants.BUSINESS_BINDER_PREFIX  + phone;
        }

        //调用方法发送验证码
        sendCode(businessKey);
    }

    private void sendCode(String businessKey) {
        //二，判断验证码是否可用（有没有超过三分钟）
        //String key = BaseConstants.BUSINESS_REGISTER_PREFIX + phone;

        //把获取验证码
        String key = businessKey;

        Object codeValueTmp = redisTemplate.opsForValue().get(key);

        //有效，没超过三分钟，
        String code = "";
        if (codeValueTmp != null) {
            //获取验证码时间,以:分割
            String[] split = ((String) codeValueTmp).split(":");
            //获取索引1的数据
            String old = split[1];
            //再将索引1的字符串转为Long类型的
            Long oldTime = Long.valueOf(old);
            //判断是否过了一分钟等待时间
            if (System.currentTimeMillis() - oldTime <= 1 * 60 * 1000) {
                //没过一分钟等待时间，说明是恶意攻击，自接踢出去
                throw new BusinessException("小老弟！！不行哦，你还嫩了点");
            } else {
                //过等待时间了,就把之前还没过期的验证码发给他
                code = ((String) codeValueTmp).split(":")[0];
            }
        } else {
            //无效，超过三分钟了，重新发送验证码
            code = StrUtils.getComplexRandomString(4);
        }
        //三，保存到数据库，并从新设置过期时间
        String codeVal = code + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, codeVal, 3, TimeUnit.MINUTES);
        //四，发短信给客户
        //SmsUtil.sendSms(param, "您的验证码是"+code+"请在三分钟之内使用，谢谢！！");
        System.out.println("您的验证码是" + code);
    }

}



